import time
from woniubook.utility import *



#图书入库
def book_in():
    from woniubook.menu import main_menu
    from woniubook.user import login_id
    # 验证身份，如果登录id为1则是管理员，否则无权入库
    if login_id[0] == 1:
        title = input("[入库]请输入书名：")
        author = input("[入库]请输入作者名：")
        publish = input("[入库]请输入出版社：")
        costprice = input("[入库]请输入进价：")
        saleprice = input("[入库]请输入售价：")
        count1 = input("[入库]请输入数量：")
        # 将图书信息写入图书信息表（bug）
        db_operation( "insert into book(title,author,publish,costprice,saleprice,count1) values ('%s','%s','%s',%f,%f,%d)" % (title,author,publish,float(costprice),float(saleprice),int(count1)))
        print("入库成功")
    else:
        print("对不起，非管理员不能入库")
    main_menu()

# 浏览图书
def scan():
    from woniubook.user import login_id
    from woniubook.menu import main_menu
    # 展示数量>0 的图书
    result = query_all("select bookid,title,author,publish,saleprice,count1 from book where count1 > 0")
    # 查询结果从元组中取出，为列表排列
    for book_info in result:
        for item in book_info:
            print(item,end="\t")
        print("")
    choose = input("请输入你的选择：【1.购买图书】  【任意键：退出】")
    if choose == '1':
        # 选择图书并加入购物车
        ############################ bug:同时购买不同的书，只有最后+购物车的书数量被减少
        bid = input("请输入要购买的图书id：")
        scount = input("请输入要购买的图书数量：")
        saleprice = query_one("select saleprice from book where bookid = %d "%(int(bid)))
        saleprice = int(scount) * saleprice[0]
        print("总价：%s" %saleprice)
        time_now = time.strftime('%Y-%m-%d %H:%M:%S')
        db_operation("insert into records (customerid,bookid,saleprice,salecount,time) values (%d,%d,%f,%f,'%s')" %(login_id[0],int(bid),saleprice,int(scount),time_now))
        print("添加购物车成功，以下为订单信息：")
        cart()
    else:
        main_menu()

# 购物车
def cart():
    from woniubook.menu import main_menu
    from woniubook.user import login_id
    # 将该用户未支付（status1 = 0）的记录展示出来
    result = query_all("select * from records where customerid = %d and status1 = 0" %login_id[0])
    book_list = []
    count_list= []
    for note in result:
    # 取出支付的图书编号、图书数量，并放进列表book_list、count_list
        book_list.append(note[3])
        count_list.append(note[5])
        for item in note:
            print(item, end="\t")
        print("")
    print(book_list)
    print(count_list)
    choose = input("请确认是否购买：【1.确认】 【任意键：返回】")
    if choose == '1':
    #判断用户的电话，地址，姓名三个关键信息是否完善，如果不完善，则提示用户补充完整。
        while '1' == '1':
            username = query_one("select username from customer where customerid = %d" %login_id[0])
            phone = query_one("select phone from customer where customerid = %d" %login_id[0])
            addr = query_one("select addr from customer where customerid = %d" %login_id[0])
            if username != None and phone != None and addr != None:
                # 图书的购买状态改为1，代表已支付，相应的图书数量减少
                db_operation("update records set status1 = 1 where customerid = %d" % login_id[0])
                ################## IndexError: list index out of range   记得加上range！！！
                for i in range(0,len(book_list)):
                    db_operation("update book set count1 = count1-%d where bookid = %d" % (int(count_list[i]),int(book_list[i])))
                print("购买成功!")
                break
            elif username == None:
                username = input("[登录]请输入用户名：")
                db_operation("update customer set username = '%s' where customerid = '%s'" %(username,login_id[0]))
            elif phone == None:
                phone = input("[登录]请输入用户名：")
                db_operation("update customer set phone = '%s' where customerid = '%s'" %(phone, login_id[0]))
            elif addr == None:
                db_operation("update customer set phone = '%s' where customerid = '%s'" %(phone, login_id[0]))
    main_menu()


# 销售记录查询
def salenote():
    from woniubook.menu import main_menu
    from woniubook.user import login_id
    # 验证身份，如果登录id为1则是管理员，否则无权查询
    if login_id[0] == 1:
        result = query_all("select * from records where status1 = 1")
        for note in result:
            for item in note:
                print(item,end="\t")
            print("")
    else:
        print("对不起，非管理员不能查询")
    main_menu()
